package view;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Line2D;
import java.util.ArrayList;

import javax.swing.ImageIcon;

import model.interfaces.IPacman;

public class PackGraphics implements Drawable {
	private IPacman pack;
	private int stateIndex,imgIndex;
	private ArrayList<Image> images;	
	private long startTime;
	private boolean debugModeOn;
	
	private static final int width = 50,height = 50;
	private static final int deltaCommon = 100,deltaDying = 200;
	private long delta = deltaCommon;
	
	// constructor
	public PackGraphics(String[] paths,IPacman pMan,boolean debugMode){
		pack = pMan;
		stateIndex = 3;
		imgIndex = 0;
		images = new ArrayList<Image>();
		startTime = System.currentTimeMillis(); 
		debugModeOn = debugMode;
		loadImgs(paths);
	}
	
	// the strings are assumed correct
	private void loadImgs(String[] imgPath){
		for (int i=0; i<20 ;i++){
			images.add(new ImageIcon(imgPath[i]).getImage());
		}
	}

	// for testing
	public void nextState(){
		stateIndex = (stateIndex+1)%5;
		resetTimerAndDelay();
	}
	
	// returns packman
	public IPacman getPack(){
		return pack;
	}
	
	// reset the timers & delays for the animation
	private void resetTimerAndDelay(){
		startTime = System.currentTimeMillis(); 
		delta = (stateIndex == 4)? deltaDying:deltaCommon;
		imgIndex = 0;
	}
	
	// changes the displayed images acording to the state
	public void changeState(int state){
		if((!pack.estaMuerto()) && (stateIndex != state)){
			stateIndex = state;
			resetTimerAndDelay();
		}
	}
	
	// draws the node 
	public void draw(Graphics g) {
		
		if (pack.estaMuerto())
			stateIndex = 4;
		updateIndex();

		int index = imgIndex+4*stateIndex;
		Image image = images.get(index);
		
		int posX = pack.obtenerPosicion().obtenerCoordenadaX();
		int posY = pack.obtenerPosicion().obtenerCoordenadaY();
		g.drawImage(image,posX-25,posY-25,width,height,null);
		
		if(debugModeOn){
			Graphics2D g2 = (Graphics2D)g;
			g2.setStroke(new BasicStroke(3));
			g.setColor(new Color(255,0,0));

			g2.draw(new Line2D.Float(posX,posY,posX,posY));	
		}
	}
	
	// updates the index for the image after certain time passes
	private void updateIndex(){
		long time = System.currentTimeMillis();
		
		if((time-startTime) > delta){
			startTime = time;

			if((stateIndex != 4) || (imgIndex != 3))
				imgIndex = (imgIndex+1)%4;
		}

	}
}
